package me.leiusual.sharing.ui.store.adapter

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import me.leiusual.sharing.ui.store.StoreAreaFragment
import me.leiusual.sharing.ui.store.StoreDetailFragment
import timber.log.Timber

/**
 * author: leiusual
 * create on: 2019-07-25
 * description:
 */
class StoreHomeAdapter(
    fragmentManager: FragmentManager
) : FragmentStatePagerAdapter(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {

  private var storeId = 0L

  private var description = ""

  private val keys = mutableListOf<Long>()

  private val values = mutableListOf<String>()

  private var categoryId = 0L

  override fun getCount(): Int {
    return keys.size
  }

  override fun getPageTitle(position: Int): CharSequence? {
    return values[position]
  }

  override fun getItem(position: Int): Fragment {
    Timber.v("getItem position = %s", position)
    return when (position) {
      0 -> StoreDetailFragment.newInstance(description)
      else -> StoreAreaFragment.newInstance(storeId, keys[position], categoryId)
    }
  }

  override fun getItemPosition(`object`: Any): Int {
    Timber.v("getItemPosition object = %s", `object`)
    if (`object` is StoreAreaFragment) {
      `object`.updateCategoryId(categoryId)
    }
    return super.getItemPosition(`object`)
  }

  fun submitMap(storeId: Long, description: String, map: Map<Long, String>) {
    this.storeId = storeId
    this.description = description

    keys.clear()
    keys.add(0, 0)
    keys.add(1, 0)
    keys.addAll(map.keys)

    values.clear()
    values.add(0, "店铺简介")
    values.add(1, "所有商品")
    values.addAll(map.values)

    notifyDataSetChanged()
  }

  fun submitCategory(categoryId: Long) {
    if (this.categoryId != categoryId) {

      this.categoryId = categoryId

      notifyDataSetChanged()
    }
  }
}